package com.zhaotianhao.check.itemserver.controller;


import com.github.pagehelper.PageInfo;
import com.zhaotianhao.check.itemserver.common.JsonResult;
import com.zhaotianhao.check.itemserver.entity.Item;
import com.zhaotianhao.check.itemserver.entity.ItemVO;
import com.zhaotianhao.check.itemserver.entity.Type;
import com.zhaotianhao.check.itemserver.service.IItemService;
import com.zhaotianhao.check.itemserver.service.ITypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Z-7
 * @since 2022-03-29
 */
@CrossOrigin
@RestController
@RequestMapping("/item")
public class ItemController {
    @Autowired
    private IItemService iItemService;
    @Autowired
    private ITypeService iTypeService;

    @GetMapping("list")
    public JsonResult list(ItemVO itemVO,@RequestParam(value = "pageNum",defaultValue = "1")int pageNum,@RequestParam(value = "pageSize",defaultValue = "3")int pageSize){
        PageInfo<Item> page = iItemService.getPageInfo(itemVO,pageNum,pageSize);
        return JsonResult.successd(page);
    }

    @GetMapping("getItems")
    public List<Item> getGroups(){
        return iItemService.list();
    }

    @GetMapping("types")
    public List<Type> getTypes(){
        return iTypeService.list();
    }

    @PostMapping("deleteById")
    public JsonResult deleteById(@RequestBody ItemVO itemVO){
        boolean flag = iItemService.removeByIds(itemVO.getIds());
        if (flag) {
            return JsonResult.successd();
        }
        return JsonResult.faild("删除失败");
    }

    @PostMapping("add")
    @Transactional
    public JsonResult addItem(@RequestBody Item item) {
        // 单表添加
        iItemService.saveOrUpdate(item);
        return JsonResult.successd();
    }

    @PostMapping("groupItems")
    public String groupItems(@RequestBody ItemVO itemVO) {
        List<Item> items = iItemService.listByIds(itemVO.getIds());
        String itemNames = items.stream().map(item -> item.getItemName()).collect(Collectors.joining(","));
        return itemNames;
    }
}
